import { ref, Ref, getCurrentInstance, nextTick } from 'vue';
import _ from 'lodash';
import { commonList } from '@/api/common/common';
import type { CallBackData } from '@/components/dialog/type.d';
import type { CommonListItem } from '@/api/common/common.d';
import type * as Temp from './type.d';
import type * as Type from '@/api/readPathology/readPathology.d';
import { Message } from '@arco-design/web-vue';
import { submitDataOver } from '@/api/readPathology/readPathology';

interface CallBack {
    flag: boolean;
    status: string;
}

export default function useToolBarRight(
    radioVisible: Ref<boolean>, 
    radioChecked: Ref<boolean | undefined>, 
    // seriesSettings: Ref<Temp.ShowComponentObj[] | null>, 
    seriesSetFormRef: Ref<any>,
    mjorSignsFormRef: Ref<any>,
    currentMiniSeriesSet: Ref<Temp.ShowComponentObj>,
    currentSubmenuItem: Ref<string | number>,
    showLesionList: Ref<Temp.NidusList[]>,
    arListData: Ref<Type.ArItem[] | null>
) {

    // 标记废片显示值
    const markScrapVisible = ref<boolean>(false);

    // 标记废片选项集合
    const scrapList = ref<CommonListItem[]>([]);

    // 标记废片选项值
    const scrapValue = ref<string>('');
    // 标记废片备注值
    const discardRemark = ref<string>('');

    // 标记废片点击
    const handleMarkDesert = () => {
        initScrapData();
    };

    // 标记废片弹窗事件
    const handleMarkScrapVisible = async (data: CallBackData) => {
        if (data.status === 'save') {
            data.done(true);
            const params = {
                arIdList: arListData.value! && [arListData.value[0].id],
                status: 3,
                discardCode: scrapValue.value,
                discardRemark: discardRemark.value
            }
            const res = await submitDataOver(params);
            Message.success('保存成功！');
            markScrapVisible.value = data.flag;
            setTimeout(() => {
                window.opener = null;
                window.open('', '_self');
                window.close();
            }, 1000);
        } else {
            scrapValue.value = '';
            discardRemark.value = '';
            markScrapVisible.value = data.flag;
        }
    };

    // 提交显示值
    const submitVisible = ref(false);

    // 提交
    const handleSubmit = () => {
        submitVisible.value = true;
    };
    let tempType = '';
    // 提交弹窗事件
    const handleSubmitVisible = (data: CallBack) => {
        tempType = data.status;
        if (data.status === 'save') {
            // 单序列提交
            validateForm(data.flag);
        } else {
            // 多序列提交
            validateForm(data.flag);
        }
    };
    let currentIndex = 0;
    let seriesFormStatus = false;
    let mjorSignsFormStatus = false;
    // 校验表单
    const validateForm = async (flag: boolean) => {
        // 判定阴阳性是否选择
        if (radioVisible.value && radioChecked.value === undefined) {
            Message.error({
                content: '请选择阴阳性，再提交病理切片！',
                closable: true,
                duration: 10000
            });
        } else {
            if (seriesSetFormRef.value) {
                // 处理大征象
                const seriesValidateRes = await seriesSetFormRef.value?.validate();
                if (seriesValidateRes === undefined) {
                    seriesFormStatus = true;
                    // 从病灶列表第一项开始依次聚焦来衔接小征象的校验
                    submitVisible.value = flag;
                    const showLesionListVal = showLesionList.value;
                    if (showLesionListVal.length) {
                        const oneDisease = _.cloneDeep(showLesionListVal[currentIndex].disease);
                        currentSubmenuItem.value = '';
                        currentMiniSeriesSet.value = _.cloneDeep({
                            formId: 0,
                            formOptions: [],
                            form: {}
                        });
                        currentSubmenuItem.value = oneDisease.id;
                        currentMiniSeriesSet.value = _.cloneDeep(oneDisease.list);
                    }
                    // 处理小征象
                    nextTick(async () => {
                        const mjorSignsRes = await mjorSignsFormRef.value?.validate();
                        if (mjorSignsRes === undefined) {
                            submitVisible.value = flag;
                            _validateForm(currentIndex, flag);
                        } else {
                            // 弹出错误信息
                            Object.keys(mjorSignsRes).forEach(key => {
                                Message.error({
                                    content: `标注征象-${mjorSignsRes[key].label}不可为空！`,
                                    closable: true,
                                    duration: 10000
                                })
                            })
                            submitVisible.value = flag;
                        }
                    })
                } else {
                    // 弹出错误信息
                    Object.keys(seriesValidateRes).forEach(key => {
                        Message.error({
                            content: `序列征象-${seriesValidateRes[key].label}不可为空！`,
                            closable: true,
                            duration: 10000
                        })
                    })
                }
                submitVisible.value = flag;
            }
        }
        
    };

    // 校验小征象辅助函数
    const _validateForm = async (index: number, flag: boolean) => {
        if (index === showLesionList.value.length - 1) {
            mjorSignsFormStatus = true;
            submitVisible.value = flag;
            if (seriesFormStatus && mjorSignsFormStatus && tempType === 'save') {
                const params = {
                    arIdList: arListData.value! && [arListData.value[0].id],
                    status: 2
                }
                const res = await submitDataOver(params);
                Message.success('保存成功！');
                submitVisible.value = flag;
                setTimeout(() => {
                    window.opener = null;
                    window.open('', '_self');
                    window.close();
                }, 1000);
            } else {
                if (arListData.value?.length && arListData.value?.length <= 1) {
                    sectionVisible.value = true;
                } else {
                    const params = {
                        arIdList: arListData.value! && [arListData.value[0].id],
                        status: 2
                    }
                    const res = await submitDataOver(params);
                    Message.success('保存成功！');
                    submitVisible.value = flag;
                    arListData.value?.splice(0, 1)!;
                    if (arListData.value?.length === 0) {
                        sectionVisible.value = true;
                    } else {
                        setTimeout(() => {
                            window.opener = null;
                            window.open(window.location.href, '_self');
                        }, 1000);
                    }
                }
            }
            return;
        } else {
            index++;
        }
        const showLesionListVal = showLesionList.value;
        if (showLesionListVal.length) {
            const oneDisease = _.cloneDeep(showLesionListVal[index].disease);
            currentSubmenuItem.value = '';
            currentMiniSeriesSet.value = _.cloneDeep({
                formId: 0,
                formOptions: [],
                form: {}
            });
            currentSubmenuItem.value = oneDisease.id;
            currentMiniSeriesSet.value = _.cloneDeep(oneDisease.list);
        }
        nextTick(async () => {
            const mjorSignsRes = await mjorSignsFormRef.value?.validate();
            if (mjorSignsRes === undefined) {
                _validateForm(index, flag);
            } else {
                // 弹出错误信息
                Object.keys(mjorSignsRes).forEach(key => {
                    Message.error({
                        content: `标注征象-${mjorSignsRes[key].label}不可为空！`,
                        closable: true,
                        duration: 10000
                    })
                })
                submitVisible.value = flag;
            }
        })
    }

    // 已无新切片弹窗显示值
    const sectionVisible = ref(false);

    // 无新切片点击事件
    const handleSectionVisible = (data: CallBackData) => {
        if (data.status === 'save') {
            data.done(true);
            sectionVisible.value = data.flag;
            setTimeout(() => {
                window.opener = null;
                window.open('', '_self');
                window.close();
            }, 1000);
        }
    };

    // 获取废片原因配置
    const initScrapData = async () => {
        // 获取废片原因
        const res = await commonList();
        const { discardReasons, ...newRes } = res?.data;
        scrapList.value = discardReasons!;
        markScrapVisible.value = true;
    }

    return {
        markScrapVisible,
        submitVisible,
        sectionVisible,
        scrapList,
        scrapValue,
        discardRemark,
        handleMarkDesert,
        handleSubmit,
        handleMarkScrapVisible,
        handleSubmitVisible,
        handleSectionVisible
    };
};